import $api from "@/api/index";
import { APIPagination } from "@/models/common";
import { useCallback, useEffect, useState } from "react";
import { CreateEventI, EventI } from "@/models/events";
import { AxiosResponse } from "axios";
import { downloadBlob } from "@/pages/gantt/helpers";

export async function getEvents(
  params?: URLSearchParams | null
): Promise<APIPagination<EventI>> {
  const res = await $api.get("api/service/event/", {
    params,
  });

  return res.data;
}

export async function getNewEvents(): Promise<EventI[]> {
  const res = await $api.get("api/service/event/new_events/");

  return res.data;
}

export function useEvents(
  params?: URLSearchParams | null
): [
  APIPagination<EventI> | undefined,
  EventI[] | undefined,
  boolean,
  (d: APIPagination<EventI>) => void
] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<APIPagination<EventI>>();

  const load = useCallback(async () => {
    if (params && params.get("month") === "1") return;
    setLoading(true);

    try {
      const r = await getEvents(params);
      setData(r);
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    load();
  }, [load]);

  return [data, data?.results || [], isLoading, setData];
}

export function useNewEvents(): [EventI[] | undefined, boolean] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<EventI[]>([]);

  const load = useCallback(async () => {
    setLoading(true);

    try {
      const r = await getNewEvents();
      setData(r);
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  return [data, isLoading];
}

export const createEventApi = async (event: CreateEventI) => {
  const res = await $api.post(`api/service/event/`, event);

  return res.data;
};

export const patchEventApi = async (
  id: number,
  event: Partial<CreateEventI>
) => {
  const res = await $api.patch(`api/service/event/${id}/`, event);

  return res.data;
};

export async function generateScheduleReport(
  month: number,
  year: number
): Promise<void> {
  const res = await $api.post<Blob>(
    `api/service/schedule_report/`,
    { month, year },
    {
      responseType: "arraybuffer",
    }
  );
  const blob = new Blob([res.data], {
    type: res.headers["content-type"],
  });

  downloadBlob(blob, `schedule_report_${year}_${month}.xlsx`);
}
